package JAVA;

import javax.swing.plaf.synth.SynthDesktopPaneUI;

class Solution {
    public int strToInt(String str) {
        
        int head = -1, tail = -1;
        for (int i = 0; i < str.length(); i++) {
            char x = str.charAt(i);
            // 开始计数，数字或者负号
            if( head == -1 && (x < '0' || x > '9') && x != ' ' && x != '-')
                return 0;
            if((x == '-' || x >= '0' && x <= '9') && (head == -1)){
                head = i;
            }
            // 溢出，这里只是粗略估算，还需要细节估算
            else if(head != -1 && i - head + 1 > 10)
                if(str.charAt(head) == '-')
                    return Integer.MIN_VALUE;
                else
                    return Integer.MAX_VALUE;
            // 非数字开始结尾
            else if(head != -1 && (x < '0' || x > '9')){
                tail = i-1;
                break;
            }
            // 特殊情况最后一个字符
            else if(i == str.length()-1 && x >= '0' && x <= '9' ){
                tail = i;
                break;
            }
        }
        int num = 0;
        String newstr = str.substring(head,tail+1);
        System.out.println(newstr);
        int length = newstr.length();
        if(newstr.charAt(0) == '-'){
            for (int i = length - 2; i >= 0 ; i++) {
                num -= (str.charAt(i) - '0')*Math.pow(10, length - i - 1);
            }
        }
        else{
            for (int i = 0; i < length ; i++) {
                num += (str.charAt(i) - '0')*Math.pow(10, length - i - 1);
            }
        } 
        return num;
    }
}